package com.ruoyi.hr.service.impl.entryexitmanage.entrymanage;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.hr.domain.Authority;
import com.ruoyi.hr.domain.Tree;
import com.ruoyi.hr.mapper.SkyMsgAlarmMapper;
import com.ruoyi.hr.mapper.entryexitmanage.entrymanage.NewEmpRegisterMapper;
import com.ruoyi.hr.service.entryexitmanage.entrymanage.NewEmpRegisterService;
import com.ruoyi.hr.util.BaseResult;
import com.ruoyi.hr.util.ResultEnum;
import com.ruoyi.hr.util.TreeBulid;
import com.ruoyi.hr.util.utils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NewEmpRegisterServiceImpl implements NewEmpRegisterService {

    @Autowired
    NewEmpRegisterMapper newEmpRegisterMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SkyMsgAlarmMapper skyMsgAlarmMapper;

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public List<Map<String, Object>> findEmpData(Map map, Authority authority) {
        return newEmpRegisterMapper.findEmpData(map, authority);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public List<Map<String, Object>> findAllTree() {
        return newEmpRegisterMapper.findAllTree();
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public int addNewEmp(Map map) {
        SysUser user = ShiroUtils.getSysUser();
        map.put("user", sysUserMapper.selectSkySecUser(user.getLoginName()));
        return newEmpRegisterMapper.addNewEmp(map);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public int editNewEmp(Map map) {
        return newEmpRegisterMapper.editNewEmp(map);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public String getJobGrade(String jobId) {
        return newEmpRegisterMapper.getJobGrade(jobId);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public String getGender(String CertType, String CertNo) {
        return newEmpRegisterMapper.getGender(CertType, CertNo);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public String getBirthDay(String CertType, String CertNo) {
        return newEmpRegisterMapper.getBirthDay(CertType, CertNo);
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public Map<String, Object> finEmpDataById(int id) {
        String[] files = {"badge", "name", "compIId", "DepIId", "JobIId",
                "JobGrade", "ReportTo", "ReportToIId",
                "WFReportTo", "WFReportToIId", "EmpTypeIId", "hxgg", "WorkCity", "WorkCityIId",
                "EMail", "officePhone", "archiveid", "JoinTypeIId", "CyearAdjust", "WorkBeginDate",
                "PracBeginDate", "PracTerm", "PracEndDate", "ProbBeginDate", "ProbTerm", "ProbEndDate", "ConTypeIId",
                "ConPropertyIId", "ContractIId", "ConBeginDate", "ConTerm", "ConEndDate", "NationIId", "CertTypeIId",
                "CertNo", "Gender", "GenderIId", "BirthDay", "Resident", "certaddress", "JoinDate", "MarriageIId",
                "PartyIId", "army", "leavearmy", "HighLevelIId", "highschool", "highenddate", "Major", "HighTitle", "Address",
                "Tel", "eMailPers", "EmergencyName", "emergencytel", "Constellation", "QQ", "Wechart", "Remark"};
        Map<String, Object> map = newEmpRegisterMapper.finEmpDataById(id);
        for (int i = 0; i < files.length; i++) {
            if (!map.containsKey(files[i])) {
                map.put(files[i], "");
            }
        }
        return map;
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public int remove(String ids) {
        String[] ids1 = ids.split(",");
        int num = 0;
        for (String id : ids1) {
            num += newEmpRegisterMapper.remove(id);
        }
        return num;
    }


    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public BaseResult procedure(String allId, String procedure) {
        //叠加异常信息
        String msgAdd = "";
        try {
            //存储过程sql
            String sql = "";
            SysUser user = ShiroUtils.getSysUser();
            Map<String, Object> maps = sysUserMapper.selectSkySecUser(user.getLoginName());
            String[] array = allId.split(",");
            String msg;//异常信息
            for (String id : array) {
                //根据id取出人名
                String name = newEmpRegisterMapper.getNameById(id);
                if (procedure.equals("eSP_StaffCheck")) {
                    sql = "declare @RetVal varchar(50) exec eSP_StaffCheck " + id + "," + maps.get("id").toString() + ",@RetVal output select @RetVal";
                } else if (procedure.equals("eSP_StaffCancel")) {
                    sql = "declare @RetVal varchar(50) exec eSP_StaffCancel " + id + "," + maps.get("id").toString() + ",@RetVal output select @RetVal";
                } else if (procedure.equals("eSP_Staffbadge")) {
                    sql = "declare @RetVal varchar(50) exec eSP_Staffbadge " + id + ",@RetVal output select @RetVal";
                } else if (procedure.equals("eSP_StaffStart")) {
                    sql = "declare @RetVal varchar(50) exec eSP_StaffStart " + id + "," + maps.get("id").toString() + ",@RetVal output select @RetVal";
                }
                msg = "";
                List<List<Map<String, Object>>> retVal = newEmpRegisterMapper.ExProcedure(sql);
                //如果大小为1直接取出返回值，先判断是否有key,再判断是否为数字执行
                if (retVal.size() == 1) {
                    if (((Map) retVal.get(0)).containsKey("")) {
                        String by = ((Map) retVal.get(0)).get("").toString();
                        if (utils.isInteger(by)) {
                            msg = skyMsgAlarmMapper.getMsgById(((Map) retVal.get(0)).get("").toString());
                        }
                    }
                } else {
                    for (List<Map<String, Object>> list : retVal) {
                        for (Map<String, Object> map : list) {
                            if (map.containsKey("")) {
                                String by = map.get("").toString();
                                if (utils.isInteger(by)) {
                                    msg += skyMsgAlarmMapper.getMsgById(map.get("").toString());
                                }
                            }
                        }
                    }
                }
                if (msg != null && !msg.equals("") && !msg.equals("null")) {
                    msgAdd += name + ":" + msg + "\n";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResult.build(ResultEnum.SERVER_ERROR);
        }
        if ("".equals(msgAdd)) {

            if (procedure.equals("eSP_StaffCheck")) {
                return BaseResult.build(ResultEnum.SERVER_ERROR, "数据确认成功!");
            } else if (procedure.equals("eSP_StaffCancel")) {
                return BaseResult.build(ResultEnum.SERVER_ERROR, "取消确认成功!");
            } else if (procedure.equals("eSP_Staffbadge")) {
                return BaseResult.build(ResultEnum.SERVER_ERROR, "工号分配成功!");
            } else if (procedure.equals("eSP_StaffStart")) {
                return BaseResult.build(ResultEnum.SERVER_ERROR, "执行入职成功!");
            }
            return BaseResult.build(ResultEnum.SUCCESS);
        } else {
            return BaseResult.build(19970926, msgAdd, null);
        }
    }

    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public int removeLargeTwoMonths() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        int count = 0;
        try {
            //1.先取出所有入职登记的数据(还没有确认检查),取出每个登记时间的第二个月作为过期日期
            //2.取出当前时间,再拿后两个月的数据和当前时间比较,如果后者大于前者，则删除
            List<Map<String, Object>> empDataList = newEmpRegisterMapper.findEmpDataAll();
            for (Map map : empDataList) {
                //循环取出每一条记录的过期日期
                String expirationDate = newEmpRegisterMapper.expirationDate(map.get("RegDate").toString());
                //取出当前日期,如果当前日期比过期日期大，则删除
                String currentDate = df.format(new Date());
                if (df.parse(currentDate).after(df.parse(expirationDate))) {
                    //如果当前日期比过期日期大,则过期,即删除
                    String id = map.get("id").toString();
                    count += newEmpRegisterMapper.remove(id);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return count;
    }
}
